<?php

/*
    Open Designs Content Management System (odCMS)
    Copyright (C) 2010  Thomas Wong - tom@ztml.org

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
*/

class localFunctions

{
	/*---------------------------\
	| initialize local functions |
	\---------------------------*/
	function localFunctions()
	{
		if($_REQUEST['set'] == "register")
		{
			if($this->memberSignup()) return;
		}
		if($_REQUEST['delete_member'])
		{
			$this->deleteMember($_REQUEST['delete_member']);
			exit;
		}

		switch($this->_CC_['Page'])
		{
			case '_menus_':
			case '_sections_':
			case '_profile_':
			case '_invite_':
			case '_users_':
			case '_templates_':
			case '_designer_':
			case '_cpanel_':	 $this->_CC_['theme'] = "cpanel";
						 return;
						 
			case '_members_':	 $this->_CC_['theme'] = "odcms_2";
						 return;
						 
			case '_upgrade_':
			case '_sitemap_':
			case 'login':
			case '_designs_':	 $this->_CC_['theme'] = "signup";
						 return;
		}

		return;
	}
	
	/*---------------\
        | update profile |
        \---------------*/
	function controlPanel()
	{
		$this->_CC_['content'] = $this->getTplMsg("odcms_cpanel");
	}

        /*-------------\
        | update menus |
        \-------------*/
	function updateMenus()
	{
		$this->_CC_['content'] = $this->getTplMsg("cpanel_menus");
	}
	
	/*---------------\
        | update profile |
        \---------------*/
	function updateProfile()
	{
		$this->_CC_['content'] = $this->getMemberProfile("update_profile");
	}

	/*-------------\
        | manage users |
        \-------------*/
	function manageUsers()
	{
		$this->_CC_['content'] = $this->getTplMsg("cpanel_users");
	}
	
	/*-----------------\
        | manage templates |
        \-----------------*/
	function manageTemplates()
	{
		$this->_CC_['content'] = "This function is not available for this account";
		//$this->_CC_['content'] = $this->getTplMsg("cpanel_templates");
	}
	
        /*--------------\
        | delete member |
        \--------------*/
	function deleteMember($mname)
	{
		if($_SESSION['UserName'] != "admin") return;
		
		$this->removeDirectory("./users/$mname");
		
		$this->MEMBERS->query("DELETE FROM members WHERE ID='$mname'");
		$this->MEMBERS->query("DELETE FROM activities WHERE UID='$mname'");
		
		$this->_CC_['page'] = "?Page=_members_";
		$this->opMessage("reload_page");
		exit;
	}
	
        /*-----------------\
        | remove directory |
        \-----------------*/
	function removeDirectory($dir)
	{
		$this->_CC_['status'] =  "";
		$handle = @opendir($dir);
		if(!$handle)
		{
			$this->_CC_['status'] .= "<font color='red'>Unable to open $dir.</font><br /><br />";
			return;
		}
		while (false !== ($file = readdir($handle)))
		{
			if($file[0] == ".") continue;
			if(is_dir("$dir/$file")) $this->removeDirectory("$dir/$file");
			else
			{
				if(@unlink("./$dir/$file")) $this->_CC_['status'] .= "$dir/$file deleted.<br />";
			else $this->_CC_['status'] .= "<font color='red'>Error encountered deleting $dir/$file.</font><br />";
			}
		}
		if(@rmdir($dir)) $this->_CC_['status'] .= "Directory $dir/$file deleted.<br /><br />";
		else $this->_CC_['status'] .= "<font color='red'>Error encountered deleting directory $dir.</font><br /><br />";
	}
	
        /*------------------\
        | get local content |
        \------------------*/
	function showLocalContent($pname)
	{
		$this->_CC_['content'] = "Page <i>$pname</i> is under contruction!";
	}

        /*---------------\
        | local database |
        \---------------*/
	function localDbase()
	{
		
	}
	
	/*----------------------\
	| process member signup |
	\----------------------*/
	function memberSignup()
	{
		$this->_CC_['Page'] = "_CC_"; // do not get page content
		$this->_CC_['theme'] = "signup";
		if($_SESSION['UserName'] && $this->cwd == $_SESSION['CWD'])
		{
			$this->_CC_['content'] .= $_SESSION['UserName']." - You cannot create an account while you're logging in.";
			return 1;
		}

		$this->_CC_['title']   = "Create Account";
		$this->_CC_['content'] = "<img src='../templates/img/signup.jpg' /><h2>Member Sign Up</h2><br />";
		
		$this->_CC_['zipcode'] = $_REQUEST['zipcode'];
		$this->_CC_['zip4']    = $_REQUEST['zip4'];
		$this->_CC_['fname']   = $_REQUEST['fname'];
		$this->_CC_['lname']   = $_REQUEST['lname'];
		$this->_CC_['city']    = $_REQUEST['city'];
		$this->_CC_['state']   = $_REQUEST['state'];
		$this->_CC_['email']   = $_REQUEST['email'];
		$this->_CC_['profile'] = $_REQUEST['profile'];
		$this->_CC_['password']= $_REQUEST['password'];
		$this->_CC_['cname']   = $_REQUEST['cname'];
		$this->_CC_['ctitle']  = $_REQUEST['ctitle'];
		$this->_CC_['slogan']  = $_REQUEST['slogan'];
		$this->_CC_['uname']   = $_REQUEST['uname'];
		
		$uname = preg_replace("/[^a-zA-Z0-9]+/", "", $_REQUEST['uname']);
		
		if(!$_REQUEST['email'])
		{
			$this->_CC_['err'] = "missing EMail;";
		}
		elseif (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $_REQUEST['email']))
		{
			$this->_CC_['err'] = "invalid EMail (".$_REQUEST['email'].");";
		}
		else
		{
			$q = $this->MEMBERS->query("SELECT ID FROM members WHERE eMail='".$_REQUEST['email']."'");
			list($id) = $q->fetch();
			if($id)
			{
				$this->_CC_['err'] = "EMail (".$_REQUEST['email'].") is already used by another member;";
			}
		}
		if(!$this->_CC_['city'] && !$this->_CC_['state'])
		{
			$this->ZIPS = new SQLiteDatabase("../zips.dbf"); // zipcodes database
			$q = $this->ZIPS->query("SELECT City,State FROM zipcodes WHERE zipcode='".$this->_CC_['zipcode']."'");
			list($this->_CC_['city'],$this->_CC_['state']) = $q->fetch();
		}
		if(!$uname)
		{
			$this->_CC_['err'] .= " missing user name;";
		}
		if (is_dir("./users/$uname"  ))
		{
			$this->_CC_['err'] .= " user name $uname exists;";
		}

		if(!$_REQUEST['password']) $this->_CC_['err'] .= " missing password;";
		if(!$this->_CC_['fname']||!$this->_CC_['lname']) $this->_CC_['err'] .= " missing first/last name;";

		if(!$this->_CC_['err'])
		{
			if(!$this->createMemberSite($uname,$this->_CC_['fname'],$this->_CC_['lname'],$this->_CC_['email'],$_REQUEST['password'],
				$this->_CC_['profile'],$this->_CC_['cname'],$this->_CC_['ctitle'],$this->_CC_['slogan'],
				$this->_CC_['zipcode'],$this->_CC_['zip4'],0,$this->_CC_['city'],$this->_CC_['state'],$from,$invite))
			{
				return;
			}
		}
		if($_POST['set']) $this->_CC_['content'] .= "<p>Please correct the following errors: <span  style='color: red'>".$this->_CC_['err']."</span></p>";
		$this->_CC_['content'] .= $this->getTplMsg("signup_profile_top").$this->getTplMsg("signup_profile_bottom");
		
		return 0;
	}
	
	/*-------------------\
	| create member site |
	\-------------------*/
	function createMemberSite($uname,$fname,$lname,$email,$pword,$profile,$cname,$title,$slogan,
				  $zip,$zip4,$dist,$city,$state,$from,$invite)
	{
		if(!$uname || !$fname || !$lname || !$pword)
		{
			$this->_CC_['content'] .= "<font size='4' color='red'>Your input data is incomplete.</font><p> Please check and re-submit.</p>";
			return 1;
		}
		$this->_CC_['uname'] = $this->username = $uname;
		$this->makeDirectory("./users/$uname");
		$this->makeDirectory("./users/$uname/images");
		
		$password = crypt($pword,$uname);
		$date     = $this->_CC_['datetime'];
		
		$this->createMember($uname,"$fname $lname",$email,$zip,$dist,$state,$city,$cname,$profile,$from,$invite);
		$this->addProfile($uname,$zip,$dist,$fname,$lname,$password,$email,$city,$state,$profile,$cname,$title,
				 $slogan,"&copy; $fname $lname","smarkup.edt","PopUp","default",$date,$date);

		$path = "./users/$uname/images/";
		if($_FILES['logo']['tmp_name'])
		{
			$this->resizeImage($_FILES['logo']['tmp_name'],0,$path."full",$path."thumb",1);
		}
		else
		{
			$img = @file_get_contents("../images/logo.jpg");
			$fp = fopen($path."thumb.jpg","w");
			fwrite($fp, $img);
		}
		$this->_CC_['page'] = "?Page=Home&member=$uname";
		$this->opMessage("reload_page");
		exit;
		
		return 0;
	}
	
        /*----------------------------\
        | create new member databases |
        \----------------------------*/
	function createMember($uname,$name,$email,$zip,$dist,$state,$city,$company,$profile,$from,$invite)
	{
		$this->UDB = new SQLiteDatabase("./users/$uname/contents.dbf"); // user content database
		
		$this->createDbase("menu","menu1");
		$this->UDB->query("INSERT INTO menu1 VALUES('Home','1','menu1^','Document','','','Home Page','','','','".
				  $this->_CC_['datetime']."')");
		
		$this->createDbase("document","Document");
		$content  = sqlite_escape_string($this->getTplValue("msgs","new_member_home_page"));
		$this->UDB->query("INSERT INTO Document VALUES('Home','1','Document','Home',".
				  "'$content','".$this->_CC_['datetime']."')");

		$profile  = sqlite_escape_string(stripslashes($profile));
		$name     = sqlite_escape_string(stripslashes($name));
		$company  = sqlite_escape_string(stripslashes($company));
		$datetime = $this->_CC_['datetime'];
		if( !file_exists("./members.dbf") )
		{
			$this->MEMBERS = new SQLiteDatabase("./members.dbf"); // members database
			$this->createDbase("member","members");
		}
		else
		{
			$this->MEMBERS = new SQLiteDatabase("./members.dbf"); // members database
		}
		$q = $this->MEMBERS->query("SELECT Points,Credits FROM points WHERE Action='Signup'");
		list($points,$credits) = $q->fetch();
		
		$q = $this->MEMBERS->query("SELECT Credits FROM points WHERE Action='cLimit'");
		list($climit) = $q->fetch();
		$this->MEMBERS->query("INSERT INTO members VALUES('$uname','$email','$name','$zip','$dist','$city','$state','$company','$profile',".
				      "'0','$points','0','0','$credits','0','$climit','$datetime','$datetime','','0','0','0')");

		$this->createDbase("transaction","transactions");
		$this->UDB->query("INSERT INTO transactions VALUES('$datetime','None','Signup Bonus','$from','$points','$credits')");

		$q = $this->MEMBERS->query("SELECT points FROM members WHERE ID='$from'");
		list($earned) = $q->fetch();
		$earned += $points;
		$this->MEMBERS->query("UPDATE members SET Points='$earned' WHERE ID='$from'");

		$this->MEMBERS->query("INSERT INTO activities VALUES(NULL,'signup','$uname','$name','signed up','?Page=Profile&member=$uname','$datetime')");
		
		if($invite)
		{
			$this->INVITES = new SQLiteDatabase("./invitations.dbf"); // invitations database
			$this->INVITES->query("UPDATE invites SET sdate='$datetime' WHERE Invite='$invite'");
		}
	}
}
?>
